package uk.gov.swmprobation.cpvisibility;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapController;
import org.osmdroid.views.MapView;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

public class ProjectReview extends MyActivity {
	
	private NodeList nodes;
	private Project project = new Project();
	private int id;
	private int projectid;
	private boolean updated;
	private ImageButton followbutton;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_project_review);
        Bundle extras = getIntent().getExtras();
        followbutton = (ImageButton) findViewById(R.id.followbutton);
        projectid = extras.getInt("project_id");
        updated = extras.getBoolean("updated", false);
        id = DatabaseHandler.getLocalId(projectid);
        if(id>0) project = DatabaseHandler.getProject(id);
        
        if (!updated){ //Can use data in database
        	ShowProject();
        } else { //Download data
        	new GetXMLAsyncTask().execute();
        }
        
        if (id>0){
	        followbutton.setEnabled(false);
        }
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.application_menu, menu);
		return true;
	}

	public void searchProjects(View view) {
    	//Get GPS co-ordinates
	    // TODO check gps data available
	    double lat = project.getLat();
	    double lng = project.getLng();
		Intent searchNearby = new Intent(this,SearchProjects.class);
		searchNearby.putExtra("lat", lat);
		searchNearby.putExtra("lng", lng);
	    startActivity(searchNearby);
    }
	
	public void followProject(View v) 
    {   
        project.setProjectType(Project.TYPE_FOLLOW);
        DatabaseHandler.addProject(project);
        
        finish();
    }
	
	public void deleteProject(View v) 
    {       
        int localId = project.getId();
        
        DatabaseHandler.deleteProject(localId);
        
        finish();
    }
	
	private void ShowProject(){
		TextView text = (TextView) findViewById(R.id.project_name);
        text.setText(String.valueOf(project.getProjectName()));
        
        text = (TextView) findViewById(R.id.project_status);
        text.setText(String.valueOf(project.getProjectStatus()));
        if (project.getProjectStatus().equals("new")) {
        	text.setTextColor(getResources().getColor(R.color.New));
        }
        else {
        	text.setTextColor(getResources().getColor(R.color.Default));
        }

    	MapView myOpenMapView = (MapView)findViewById(R.id.openmapview);
        myOpenMapView.setBuiltInZoomControls(false);
        myOpenMapView.setClickable(false);
        MapController myMapController = myOpenMapView.getController();
        myMapController.setZoom(16);
        GeoPoint point = new GeoPoint(project.getLat(), project.getLng());
        myMapController.setCenter(point);
        
        if(project.getProjectType()==Project.TYPE_FOLLOW){
        	followbutton.setVisibility(View.GONE);
        	ImageButton deletebutton = (ImageButton) findViewById(R.id.deletebutton);
        	deletebutton.setVisibility(View.VISIBLE);
        }
	}
	
	public class GetXMLAsyncTask extends
    AsyncTask<Void, Integer, String> {
		
		@Override
		protected String doInBackground(Void... arg0) {
			
			String url = "http://env-2768543.jelastic.dogado.eu/geovation/project.xql?id="+projectid;
			String xmlString = XMLfunctions.getXML(url);

			return xmlString;
		}
		
		@Override
		  protected void onPostExecute(String xmlString) {
			
			String imageUrlString = null;
			
			if (xmlString != "failed"){
			Document doc = XMLfunctions.XMLfromString(xmlString);
			nodes = doc.getElementsByTagName("document");
			for (int i = 0; i < nodes.getLength(); i++) {
				Element e = (Element)nodes.item(i);
				project.setLat(Double.parseDouble(XMLfunctions.getValue(e, "lat")));
				project.setLng(Double.parseDouble(XMLfunctions.getValue(e, "lng")));
				project.setProjectId(projectid);
				project.setProjectName(XMLfunctions.getValue(e, "title"));
				project.setProjectStatus(XMLfunctions.getValue(e, "status"));
				project.setUpdated(false);
				imageUrlString = "http://env-2768543.jelastic.dogado.eu/geovation/"+XMLfunctions.getValue(e, "med");
				project.setImageUrl(Uri.parse(imageUrlString));
			}
			
			project.setId(id);
			if (id>0){
				project.save(); //save update if project already in database
			} else {
				project.setProjectType(Project.TYPE_NONE);
			}
			ShowProject();
			}

		  }
	}	
}
